package com.example.dmallOrder.common.dmall.util;

import com.dmall.sdk.ApiException;
import com.dmall.sdk.Constants;
import org.apache.commons.codec.binary.Base64;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.regex.Pattern;

/**
 * todo
 *
 * @author:yanbo.li
 * @date: 2023/5/23
 */
public class EncryDecryptUtil {

    public static String decrypt(String data, String appSecret) throws Exception {
        String base64Pattern = "^([A-Za-z0-9+/]{4})*([A-Za-z0-9+/]{4}|[A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{2}==)$";
        boolean isBase64 = Pattern.matches(base64Pattern, data);
        //判断是否为加密内容(非json字符串并且是Base64格式)
        boolean isDataEncrypted = (data != null && !data.isEmpty() && !data.startsWith("{") && Base64.isBase64(data) && isBase64);
        //非加密内容返回原数据
        if (!isDataEncrypted) {
            return data;
        }
        //初始化AES/CBC/PKCS5Padding加密算法实例
        Cipher cipher = Cipher.getInstance(Constants.DEFAULT_CIPHER_ALGORITHM);
        //对加密数据base64解码
        byte[] byteContent = Base64.decodeBase64(data);
        //初始化向量为固定值: byte[]{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}
        IvParameterSpec iv = new IvParameterSpec(initIv());
        //使用密钥初始化，设置为解密模式
        cipher.init(Cipher.DECRYPT_MODE, getSecretKey(appSecret), iv);
        //获取解密后数据字节
        byte[] result = cipher.doFinal(byteContent);
        //对字节使用utf-8编码,返回解密数据
        return new String(result, StandardCharsets.UTF_8);
    }



    private static SecretKeySpec getSecretKey(String appSecret) throws ApiException {
        try {
            byte[] keyBytes = appSecret.getBytes(StandardCharsets.UTF_8);
            return new SecretKeySpec(keyBytes, "AES");
        } catch (Exception var2) {
            throw new ApiException("秘钥转换错误", var2);
        }
    }


    private static byte[] initIv() {
        byte[] iv;
        int i;
        try {
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            int blockSize = cipher.getBlockSize();
            iv = new byte[blockSize];

            for(i = 0; i < blockSize; ++i) {
                iv[i] = 0;
            }

            return iv;
        } catch (Exception var4) {
            int blockSize = 16;
            iv = new byte[blockSize];

            for(i = 0; i < blockSize; ++i) {
                iv[i] = 0;
            }

            return iv;
        }
    }
}
